<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<!DOCTYPE HTML>
<html>
<head>
<title>数据质检</title>
<jsp:include page="scriptAndLink_easyui.jsp"></jsp:include>
<script type="text/javascript" src="<%=basePath%>a2zj/js/json2.js"></script> 
<link href="<%=basePath %>a2zj/css/datepicker3.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=basePath%>a2zj/js/bootstrap-datepicker.js"></script> 
<script type="text/javascript" src="<%=basePath%>a2zj/js/bootstrap-datepicker.zh-CN.js"></script> 
<script type="text/javascript" src="<%=basePath%>a2zj/js/easyui-lang-zh_CN.js"></script> 
<script>
     $(function () {
    	 $('#managerTab').datagrid({
		    columns:[[  
		   		{field:'entId',title:'entId',checkbox:true},
		   		{field:'ruleId',title:'规则id',hidden:true},
		   		{field:'projID',title:'项目id',hidden:true},
		   		{field:'projectPackageID',title:'父项目id',hidden:true},
		   		{field:'ruleName',title:'规则名称',width:200},
		   		{field:'procedureName',title:'存储过程名称',hidden:true},
		   		{field:'entType',title:'类型',hidden:true},
		   		{field:'checkContext',title:'检查内容',width:500,
		    		formatter: function(value) {
		    			if(value){
		    				value="<span title='" + value + "'>" + value + "</span>"
		    			}
		    		    return value;
		    		}
		   		}
    		]],
    		toolbar: '#tb',
		    onLoadSuccess : function(data) {
			    var rows = $("#managerTab").datagrid('getRows');
			    if(rows.length>0){
			    	$("#paramsGrid").datagrid('loadData', { total: 0, rows: [] });
					$("#paramsGrid").datagrid({
						queryParams : {},
						url:"<%=basePath%>zj/zjProcedureManager.do?method=getParamInfo&projectId="+selectedProjectId+"&ruleId="+rows[0].ruleId+"&newDate=" + (new Date()).getTime()
					});
			    }
			}
		}); 
    	var p1 = $('#managerTab').datagrid().datagrid('getPager'); 
    	$(p1).pagination({
    	        pageSize: 10,//每页显示的记录条数，默认为10 
    	        pageList: [10,20,30],//可以设置每页记录条数的列表
    	        beforePageText: '第',//页数文本框前显示的汉字 
    	        afterPageText: '页    共 {pages} 页', 
    	        displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录' 
    	}); 
    	
     	
    	//质检项目tree
        buildQualityTree();    	
        initParamGrid();
        $("#btn_qualityTestResultBtns_cancelTwo").unbind('click');
    	$("#btn_qualityTestResultBtns_cancelTwo").bind("click", function() {
    		$('#qualityTestResultWinTwo').dialog({
    			closed : true
    		});
    	});
    });
     
     
   //获取质检项目目录树
     var selectedProjectId;
     function buildQualityTree(){
     	$("#treeDemo").tree({
         	url : "<%=basePath%>zj/zjProcedureManager.do?method=buildQualityTree&newDate=" + (new Date()).getTime(),
         	animate:true,//定义当节点展开折叠时是否显示动画效果
         	onLoadSuccess:function(){
         		//关闭遮罩
     				$('#loading-mask').fadeOut();
         	},
     		onBeforeExpand:function(node){
     			var isParent = node.attributes.isParent;
     			if(isParent){
     				var childrenNode = $("#treeDemo").tree('getChildren',node.target);
     				if(childrenNode.length === 0){//当前节点下没有子节点时,不展开
     					return false;
     				}
     			}
     		},
         	onClick:function(node){
         		selectedProjectId = node.id;
         		var isParent = node.attributes.isParent;
     			if(isParent){
     				$("#treeDemo").tree('toggle',node.target);
     			}else{//叶子节点（展现该质检项目下的质检规则）
     				var parentNode = $(this).tree('getParent',node.target);
     				initRuleGrid(node.id,parentNode.id);
     			}
         	}
         });
     }

 	function initRuleGrid(prjId,projectPackageID){
		if(!prjId){
			prjId = "";
		}
		//var paramData = "{prjId:'" + prjId+"'}";
		$("#managerTab").datagrid('loadData', { total: 0, rows: [] });
		$("#managerTab").datagrid({
			queryParams : {},
			url:"<%=basePath%>zj/zjProcedureManager.do?method=getRuleInfo&prjId="+prjId+"&projectPackageID="+projectPackageID+"&newDate=" + (new Date()).getTime()
		});
			
	    
	}
 	
 	
 	function initParamGrid() {
 		$("#paramsGrid")
 				.datagrid(
 						{
 							fit : true,
 							//rownumbers : true,
 							title : "质检参数",
 							columns : QtParamColDatas,
 							fitColumns : true,
 							striped : true,
 							nowrap : true,
 							singleSelect : true,
 							showHeader:false,
 							idField : 'oid',
 							onSelect : function(rowIndex, rowData) {
 							},
 							rowStyler: function (index, row) {
 					            if (row.controlType != 'P_DATE'&&row.controlType != 'P_NY'&&row.controlType != 'P_SELECT_ORG') {//条件                    
 		                            return 'display:none';
 		                        }else{
 		                            return ;
 		                        }
 						    },
 							onLoadSuccess : function(data) {
 								var rows = data.rows;
 								if (rows && rows.length > 0) {
 									for (var rowid = 0; rowid < rows.length; rowid++) {
 										var rowData = rows[rowid];
 										var oname = rowData.oname;//参数code作为控件id的变量，参数code具有唯一性
 										var controlType = rowData.controlType;// 控件类型
 										var dateFormatter = rowData.dateFormatter;
 										var paramValue=rowData.paramValue;
 										var dataparamOtype = rowData.dataparamOtype;
 										if(dataparamOtype=='IN'){
 	 										$('#paramsGrid').datagrid(
														'updateRow',
														{index : rowid,
															row : {
																value : "<input id=\""+ rowid+ "_value\" style=\"width: 95%\"/>"
															}
										    });
 										}
 										if(controlType=="P_TEXT"){//根据参数展示类型创建不同的组件
 											if(paramValue!="" && paramValue!=null && paramValue!="undefined" && paramValue.length>0){
 												$("#" + rowid + "_value").val(paramValue);
 												
 											}
 											//$("#" + rowid + "_value").attr("readonly","readonly")
 										}else if (controlType == "P_DATE") {
 											$("#" + rowid + "_value").attr(
 													"data_rowId", rowid);
 											$("#" + rowid + "_value").datebox({
 												editable : false,
 												formatter: function (date) {return date.format("yyyy-MM-dd"); }
 	                                        });
 											if (paramValue == '未查询到数据！'
 													|| paramValue == null
 													|| paramValue == 'null'
 													|| paramValue == "undefined") {
 												$("#" + rowid + "_value").datebox("setValue",new Date().format(dateFormatter));
 												$("#" + rowid + "_paramValue").val(new Date().format(dateFormatter));
 											} else {
 												$("#" + rowid + "_value").datebox("setValue",paramValue.substr(0,10));
 											}
 										} else if (controlType == "P_TIME") {
 											$("#" + rowid + "_value").attr(
 													"data_rowId", rowid);
 											$("#" + rowid + "_value").datetimebox({
 												// width : 210,
 												editable : false
 											});
 											if (paramValue == '未查询到数据！'
 													|| paramValue == null
 													|| paramValue == 'null'
 													|| paramValue == "undefined") {
 												$("#" + rowid + "_value").datetimebox("setValue",new Date().format(dateFormatter));
 												$("#" + rowid + "_paramValue").val(new Date().format(dateFormatter));
 											} else {
 												$("#" + rowid + "_value").datetimebox("setValue",paramValue.substr(0,10));
 											}
 										} else if (controlType == "P_NY") {
 											LoadDateJSControl(rowid, dateFormatter,new Date());
 										}else if (controlType == "P_SELECT_ORG") {
 											$("#" + rowid + "_value").combobox({  
 							                    url:"<%=basePath%>zj/zjProcedureManager.do?method=getOrgList&projectId=&newDate=" + (new Date()).getTime(),
 							                    method:"post",  
 							                    panelHeight:300,//设置为固定高度，combobox出现竖直滚动条 
 							                    width:300,
 							                    valueField:"CODE",  
 							                    textField:"NAME",  
 							                    multiple:true,
 							                    onSelect :function(record){
 							                       var opt=$(this).combobox("options");
 							                       var valueField = opt.valueField;
 							                       if(!record[valueField]){
 							                          var data = $(this).combobox("getData");
 							                          var values = $(this).combobox("getValues");
 							                          var selectVaues = [];
 							                          if(data.length != values.length){
 							                        	 for(var i=0;i<data.length;i++){
  							                        		selectVaues.push(data[i].CODE);
 							                        	 }
 							                          }else{
 							                              selectVaues.push(record[valueField]);
 							                          }
 							                          $(this).combobox('setValues', selectVaues);
 							                      } 
	 											},
	 											onUnselect :function(record){
  							                       var valueField = $(this).combobox("options").valueField;
  							                       if(!record[valueField]){
    							                        $(this).combobox('setValues', "");
  							                      } 
 	 											}
	 							            }) 
 										}
 									}
 								}
 							}
 						});
 	};

 	function LoadDateJSControl(rowid, dataype, defaultDates) {
 		$("#" + rowid + "_value").datepicker({
 			format : dataype,
 			minViewMode : 1,
 			autoclose : true,
 			language : "zh-CN",
 			keyboardNavigation : false
 		});
 		$("#" + rowid + "_value").datepicker('setDate', defaultDates);

 	}
 	
 	
 	var QtParamColDatas = [ [ {
 		field : 'id',
 		title : 'xh',
 		hidden : true
 	}, {
 		field : 'parameType',
 		title : '参数数据类型',
 		hidden : true
 	}, {
 		field : 'dataParameteCode',
 		title : '参数Code',
 		hidden : true
 	}, {
 		field : 'oname',
 		title : '参数名称',
 		hidden : true
 	}, {
 		field : 'odesc',
 		title : '参数描述',
 		width : 100
 	}, {
 		field : 'dataparamOtype',
 		title : '参数类型',
 		hidden : true
 	}, {
 		field : 'controlType',
 		title : '控件类型',
 		hidden : true
 	}, {
 		field : 'dateFormatter',
 		title : '日期格式',
 		hidden : true
 	}, {
 		field : 'value',
 		title : '参数值',
 		width : 660
 	}, {
 		field : 'paramValue',
 		title : '参数combobox值',
 		formatter : customFmatter12,
 		hidden : true
 	} ] ];
 	
 	function customFmatter12(cellvalue, options, rowObject) {
 		var str = "";
 		if (cellvalue != null) {
 			str = JSON.stringify(cellvalue);
 		}
 		return str;
 	}
 	
 	Date.prototype.format = function (fmt) {
 	    var o = {
 	        "M+": this.getMonth() + 1, //月份 
 	        "d+": this.getDate(), //日 
 	        "h+": this.getHours(), //小时 
 	        "m+": this.getMinutes(), //分 
 	        "s+": this.getSeconds(), //秒 
 	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
 	        "S": this.getMilliseconds() //毫秒 
 	    };
 	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 	    for (var k in o)
 	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 	    return fmt;
 	}
 	
 	function showProcess(isShow, title, msg, text) {
 		if (!isShow) {
 			$.messager.progress('close');
 			return;
 		}
 		$.messager.progress({
 			title : title,
 			msg : msg,
 			text : text
 		});
 	}
 	
 	var ruleArray = null;
 	function runDataQualityCheck(){
 		str = "";
 		ruleArray = new Array();
 		var isParams=getRuleParams();
 		if(isParams==false){
 			return false;
 		}
 		// 获取选中行的ID
 		var selectedRows = $("#managerTab").datagrid('getSelections');
 		if (selectedRows == "undefined" || selectedRows.length == 0) {
 			$.messager.alert("系统窗口", "请选择质检规则！", "error");
 			return false;
 		}
 		// 根据行id获取每行数据
 		for (var i = 0; i < selectedRows.length;) {
 			var rowDatas = selectedRows[i];// 获取某一行的数据
 			ruleArray[i] = rowDatas;
 			i = i + 1;
 		}
 		showProcess(true, "温馨提示", "质检中.....", "");
 		// 开始时间
 		runQualityTestByProcedure(0);// 单规则逐个递归质检
 	}
 	var paramsStr;
 	function getRuleParams() {
 		var allRows = $("#paramsGrid").datagrid('getRows');
 		paramsStr = "[";
 		if (allRows == null || allRows.length == 0) {
 			paramsStr = "";
 			return false;
 		}
 		for (var i = 0; i < allRows.length; i++) {
 			var rowData = allRows[i];
 			var rowIndex = $('#paramsGrid').datagrid('getRowIndex', rowData);
 			var value = getParamValue(rowIndex, rowData.controlType);
 			if(rowData.controlType == "P_SELECT_ORG"&&value==""){
 	 			$.messager.alert("系统窗口", "请选择机构！", "error");
 	 			return false;
 			}
			var s = "{\"code\" : \""+ rowData.oname + "\",\"value\" : \"" + value
					+ "\",\"dataparamOtype\" : \"" + rowData.dataparamOtype
					+ "\",\"parameType\" : \"" + rowData.parameType
					+ "\",\"controlType\" : \"" + rowData.controlType
					+ "\"}";
			paramsStr += s + ",";
 		}
 		if (paramsStr.length > 1) {
 			paramsStr = paramsStr.substring(0, paramsStr.length - 1) + "]";
 			return paramsStr;
 		}
 		paramsStr = "";
 	}

 	
 	function getParamValue(rowid, controlType) {
 		var value = "";
 		if (controlType == "P_COMBOBOX") {
 			var paramValArray = $("#" + rowid + "_value").combobox("getValues");
 			if (paramValArray != null && paramValArray.length > 1) {
 				var paramVals = "";
 				$.each(paramValArray, function(n, val) {
 					paramVals += "" + val + ",";
 				});
 				value = paramVals.substring(0, paramVals.length - 1);
 			} else {
 				value = $("#" + rowid + "_value").combobox("getValue");
 			}
 		} else if (controlType == "P_DATE") {
 			value = $("#" + rowid + "_value").datebox("getValue");
 		} else if (controlType == "P_TIME") {
 			value = $("#" + rowid + "_value").datetimebox("getValue");
 		} else if (controlType == "P_NY") {
 			value = $("#" + rowid + "_value").val();
 		} else if (controlType == "P_SELECT_ORG") {
 			value = $("#" + rowid + "_value").combobox("getValues");
 			value=value.toString().replace(new RegExp(",","gm"),"|");
			if(value.substr(0, 1)=='|'){
				value=value.substr(1, value.length);
			}
 		}else {
 			value = $("#" + rowid + "_value").val();
 		}
 		return value;
 	}
 	
 // 执行质检方法(存储过程)
 	function runQualityTestByProcedure(number) {
 		if (number == ruleArray.length) {
 			showProcess(false);
 			$("#showHtmldiv").html(str);
 			$('#qualityTestResultWinTwo').dialog({
 				title : '存储过程规则质检结果',
 				closed : false,
 				buttons : '#div_qualityTestResultBtnsTwo'
 			});

 			return;
 		}
 		var ruleId = ruleArray[number].ruleId;
 		var procedureName=ruleArray[number].procedureName;
 		var count = number + 1;
 		showProcess(false);
 		showProcess(true, "温馨提示", "一共" + ruleArray.length + "个质检规则！", "正在质检第"
 				+ count + "个")
 		// 执行数据质量检查
     		$.ajax({
 			url : "<%=basePath%>zj/zjProcedureManager.do?method=runQualityTestByProcedure&newDate=" + (new Date()).getTime(),
 			type : 'POST',
 			async : true,
 			data : {
 				"projectId" : selectedProjectId,
 				"rules" : ruleId,
 				"procedureName" : procedureName,
 				"params" : paramsStr
 			},
 			dataType : 'json',
 			success : function(responseData) {
 				var msg = responseData.Msg;
 				str += "第" + count + "个规则，" + msg + "<br/>";// 质检消息
 				number = number + 1;
 				// 递归调用
 				runQualityTestByProcedure(number);
 			},
 			error : function(responseData) {
 				showProcess(false);
 				$.messager.alert("系统提示", "服务异常", "error");
 			}
 		});
 	}
 	if(!Array.prototype.indexOf){  
 	    Array.prototype.indexOf = function(target){  
 	        for(var i=0,l=this.length;i<l;i++){  
 	            if(this[i] === target) return i;  
 	        }  
 	        return -1;  
 	    };  
 	}
    </script>
</head>
<body class="easyui-layout" style="width: auto; height: 550px">
	<div id="loading-mask" style="position:absolute;top:0px; left:0px; width:100%; height:100%; background:#D2E0F2; z-index:20000">
	    <div id="pageloading" style="position:absolute; top:50%; left:50%; margin:-120px 0px 0px -120px; text-align:center;  border:2px solid #8DB2E3; width:200px; height:40px;  font-size:14px;padding:10px; font-weight:bold; background:#fff; color:#15428B;"> 
	    	正在加载,请稍候...
	    </div>
	</div>
<div region='west' border="true" split=true title="质检项目一览" style="width:220px; padding:0px;">
	<ul  id="treeDemo" ></ul>
</div>
<!-- 质检规则和质检参数一览 -->
<div data-options="region:'center', border:false" style="border-color:#ccc;width:100%;height:100%;">
	<div class="easyui-layout" style="border-color:#ccc;width:100%;height:100%;">
		<div data-options="region:'north',border:false" style="height: 80px;">
			<table id="paramsGrid" fit="true" border="false" ></table>
		</div>
		<div data-options="region:'center',border:false">
		<table id="managerTab" class="easyui-datagrid"
			style="width: auto; height: 800px" fit="true"></table>
		</div>
		<!-- 下部区域 -->
		<div region='south' style="height:40px;text-align:center;vertical-align:middle;padding-top:8px;padding-left:2px;">
			<!-- 质检按钮 -->
			<a id="qualityTestBtn" class="easyui-linkbutton" href="#" onclick="javascript:runDataQualityCheck()" data-options="iconCls:'icon-search'">执行质检</a>
		</div>
	</div>
</div>
<div id="qualityTestResultWinTwo" class="easyui-dialog" style="width:640px; height:400px;" data-options="closed:true, modal:true">
	<input id="serverTime" type="hidden"/>
	<div style="margin:2px;">
		<div id="showHtmldiv">		
		</div>
	</div>
	<div id="div_qualityTestResultBtnsTwo" closed="true">
		<a href="javascript:void(0)" class="easyui-linkbutton" id="btn_qualityTestResultBtns_cancelTwo" iconCls='icon-ok' style="width: auto; height: auto;"> 关 闭 </a>
	</div>
</div>	
</body>
</html>